package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.Post;
import com.scuec.groupfive.mapper.PostManagementMapper;
import com.scuec.groupfive.service.PostCommentService;
import com.scuec.groupfive.service.PostManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PostManagementServiceImpl implements PostManagementService { // 确保类名正确
    @Autowired
    private PostManagementMapper postManagementMapper;

    @Autowired
    private PostCommentService postCommentService;

    @Override
    public Long createPost(Post post) {
        post.setCreatedAt(new Date());
        post.setUpdatedAt(new Date());
        postManagementMapper.createPost(post);
        return post.getPostId();
    }

    @Override
    public boolean updatePost(Post post) {
        post.setUpdatedAt(new Date());
        int result = postManagementMapper.updatePost(post);
        return result > 0;
    }

    @Override
    public boolean deletePost(Long postId) {
        try {
            postCommentService.deleteCommentsByPostId(postId);
            int result = postManagementMapper.deletePost(postId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Post getPostById(Long postId) {
        return postManagementMapper.getPostById(postId);
    }

    @Override
    public List<Post> getAllPosts(int page, int size) {
        return postManagementMapper.getAllPosts(page, size);
    }

    @Override
    public boolean restorePost(Long postId) {
        int result = postManagementMapper.restorePost(postId);
        return result > 0;
    }

    @Override
    public List<Post> searchPosts(String title, String content) {
        return postManagementMapper.searchPosts(
                title != null ? "%" + title + "%" : null,
                content != null ? "%" + content + "%" : null
        );
    }

    @Override
    public int getTotalPostCount() {
        return postManagementMapper.getTotalPostCount();
    }
}